package emailutil

import (
	"bytes"
	"crypto/tls"
	"github.com/jordan-wright/email"
	"html/template"
	"net"
	"net/smtp"
)

type Email struct {
	Code string `json:"title"`
}

var emailTemplate = `
<div id="mailText" class="mailTextDivMG" style="display:; font-size:14px">
			<table style="font-family:'Microsoft YaHei','黑体';width:700px;margin:0 auto;border:1px solid #ccc;background-color:#fff;" cellpadding="0" cellspacing="0">
    <tbody>
        <tr>
            <td style="font-family:'Microsoft YaHei','黑体';padding:20px 30px;font-size:small;"><table style="font-family:'Microsoft YaHei','黑体';width:100%;" cellpadding="0" cellspacing="0">
    <tbody>
        <tr>
            <td style="font-family:'Microsoft YaHei','黑体';font-size:16px;">
                您好，
            </td>
        </tr>
        <tr>
            <td style="font-family:'Microsoft YaHei','黑体';font-size:14px;padding-top:20px;">
                您的注册验证码为：
                <p style="font-family:'Microsoft YaHei','黑体';color:#1e88e5;padding-top:20px;font-size:16px;margin:0;">
                    {{.Code}}
                </p>
                <p style="font-family:'Microsoft YaHei','黑体';padding-top:10px;margin:0;">
                    30分钟内输入有效
                </p>
            </td>
        </tr>
    </tbody>
</table></td>
        </tr>
    </tbody>
</table>
			</div>
`
type Options struct {
	Host     string
	Port     string
	Username string
	Password string
	SSL      bool
}


// SendTemplateEmail 发送模版邮件
func SendTemplateEmail(code string) (result string, err error) {
	tpl, err := template.New("emailTemplate").Parse(emailTemplate)
	if err != nil {
		return
	}
	var b bytes.Buffer
	err = tpl.Execute(&b, map[string]interface{}{
		"Code": code,
	})
	if err != nil {
		return
	}
	result = b.String()
	return
}

// SendEmail 发送邮件
func SendEmail(o *Options, to string, subject, html string) error {
	var (
		host      = o.Host
		port      = o.Port
		username  = o.Username
		password  = o.Password
		ssl       = o.SSL
		addr      = net.JoinHostPort(host, port)
		auth      = smtp.PlainAuth("", username, password, host)
		tlsConfig = &tls.Config{
			InsecureSkipVerify: true,
			ServerName:         host,
		}
	)
	e := email.NewEmail()
	e.From = o.Username
	e.To = []string{to}
	e.Subject = subject
	e.HTML = []byte(html)
	if ssl {
		if err := e.SendWithTLS(addr, auth, tlsConfig); err != nil {
			return err
		}
	} else {
		if err := e.Send(addr, auth); err != nil {
			return err
		}
	}
	return nil
}
